package com.xcy.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xcy.dto.User;
import com.xcy.service.IUserService;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    @RequestMapping("/userList")
    public String userList(HttpServletRequest request,Model model){
        List<User> uList = userService.getAllUser();
        model.addAttribute("uList", uList);
        return "userList";
    }

    @RequestMapping("/showUser")
    public String showUser(HttpServletRequest request,Model model){
        int userId = Integer.parseInt(request.getParameter("id"));
        User user = userService.getUserById(userId);
        model.addAttribute("user", user);
        return "showUser";
    }

    @RequestMapping("/addUserUI")
    public String addUserUI(){
        return "addUser";
    }

    @RequestMapping("/addUser")
    public String addUser(HttpServletRequest request,Model model){
        User user = new User();
        user.setName(String.valueOf(request.getParameter("name")));
        user.setPassword(String.valueOf(request.getParameter("password")));
        user.setAge(Integer.parseInt(String.valueOf(request.getParameter("age"))));
        userService.addUser(user);
        return "redirect:/user/userList";
    }

    @RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
    public String deleteById(@RequestParam(value = "id", required = true) int id){

        userService.deleteUserById(id);

        return "redirect:/user/userList";
    }

    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public String updateUser(@RequestParam(value = "id", required = true) int id,
                             @RequestParam(value = "name", required = true) String name,
                             @RequestParam(value = "password", required = true) String password,
                             @RequestParam(value = "age", required = true) int age){
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setPassword(password);
        user.setAge(age);

        userService.updateUser(user);

        return "redirect:/user/userList";
    }
}